package com.my.ecommercesystem.filter;

import com.my.ecommercesystem.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request2 = (HttpServletRequest) servletRequest;
        request2.setCharacterEncoding("utf-8");
        HttpSession session = request2.getSession();
        User user = (User) session.getAttribute("loginuser");
        if (user != null) {
            filterChain.doFilter(request2, servletResponse);
        } else {
            servletResponse.setContentType("text/html;charset=utf-8");
            PrintWriter pw = servletResponse.getWriter();
            pw.print("<script>alert('会话已失效，请重新登录');location.href='login';</script>");
        }
    }
}
